package Pages;

import java.util.*;

import clientMain.*;

/**
 * Buy Item Page
 * @author Andrew Fox
 *
 */

public class BuyItemPage extends Page{
	HashMap<String, StringBuffer> data=new HashMap<String,StringBuffer>();
	ArrayList<String> changedData=new ArrayList<String>();
	
	public BuyItemPage(Page page){
//		super(page.url,page.lastURL,page.client);
//		this.html=page.html;
//		this.pageType=page.pageType;
		super(page.url,page.html,page.client,page.pageType);
		this.pageOpenTime=page.pageOpenTime;
		this.lastURL=page.lastURL;
	}
	
	/**
	 * Determines the next link to go to in the application
	 * @return the URL or HTML of the next link, depending on whether
	 * 		   the previous entry contained a form or not
	 */
	public StringBuffer makeDecision() throws Exception{
		StringBuffer nextPage=new StringBuffer();

		
if(HTML4){
		data=getFormData();

		if (data.get("town").equals(client.userInfo.city)==false){
			data.put("town",client.userInfo.city);
			changedData.add("town");
		}
		if (data.get("street").equals(client.userInfo.address)==false){
			data.put("street",client.userInfo.address);
			changedData.add("street");
		}
		if (data.get("zip").equals(client.userInfo.zipcode)==false){
			data.put("zip",client.userInfo.zipcode);
			changedData.add("zip");
		}
		if (data.get("state").equals(client.userInfo.USStateCode)==false){
			data.put("state",client.userInfo.USStateCode);
			changedData.add("state");
		}
		
			
		
		data.put("nameOnCard", client.userInfo.firstName.append(" ").append(client.userInfo.lastName));
		data.put("creditCardNo",client.userInfo.creditCardNumber);
		data.put("cvv",client.userInfo.cvv2);
		data.put("expirationDate",client.userInfo.creditCardExpiry);
		
		if (changedData.isEmpty()==false)
			client.message="update";
		
		// Think Time
		try{Thread.sleep(getThinkTime());}
		catch(InterruptedException e){
			e.printStackTrace();
		}
		
		nextPage=doSubmit3(runSettings.rootURL.append("/buyitem?"),data,client);
}
	else{
		nextPage=runSettings.rootURL.append("/myaccount");
	}
		return nextPage;
	}
	
	/**
	 * Determines the think time before going to the next page
	 * Deducts from the think time the amount of time since the 
	 * page opened until this calculation is performed
	 * @return Think time in ms
	 */
	public int getThinkTime(){
		int thinkTime=(int)expDist(initialThinkTime);
		
		thinkTime+=Math.round((data.get("nameOnCard").length()+data.get("creditCardNo").length()+data.get("cvv").length()+data.get("expirationDate").length())/client.typingSpeed);
		for (int i=0;i<changedData.size();i++){
			thinkTime+=Math.round((data.get(changedData.get(i)).length())/client.typingSpeed);
		}
		
		
		if (verbose)System.out.println("User: "+client.userInfo.username+" - Think Time: "+thinkTime+" ms");
		return (int) ((thinkTime-(new Date().getTime()-pageOpenTime))/runSettings.thinkTimeSpeedUpFactor);
	}

}
